package cn.zhangxin.pethome.system.shop.controller;

import cn.zhangxin.pethome.system.shop.service.IShopService;
import cn.zhangxin.pethome.system.shop.domain.Shop;
import cn.zhangxin.pethome.system.shop.query.ShopQuery;
import cn.zhangxin.pethome.utils.AjaxResult;
import cn.zhangxin.pethome.utils.BusinessException;
import cn.zhangxin.pethome.utils.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/shop")
public class ShopController {
    @Autowired
    public IShopService shopService;


    /**
     * 保存和修改公用的
     *
     * @param shop 传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Shop shop) {
        try {
            if (shop.getId() != null)
                shopService.update(shop);
            else
                shopService.add(shop);
            return AjaxResult.success();
        } catch (BusinessException e) {//捕获业务异常
            return AjaxResult.error().setMsg(e.getMessage());
        } catch (Exception e) {//一般保存就不是业务异常
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常，请稍后再试");
        }
    }

    /**
     * 删除对象信息
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            shopService.delete(id);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error().setMsg(e.getMessage());
        }
    }

    //获取用户
    @GetMapping("/{id}")
    public Shop get(@PathVariable("id") Long id) {
        return shopService.findOne(id);
    }


    /**
     * 查看所有的员工信息
     *
     * @return
     */
    @GetMapping()
    public List<Shop> list() {

        return shopService.findAll();
    }


    /**
     * 分页查询数据
     *
     * @param query 查询对象
     * @return PageList 分页对象
     */
    @PostMapping("/list")
    public AjaxResult json(@RequestBody ShopQuery query) {
        try {
            List<Shop> byQuery = shopService.findByQuery(query);
            Long total = shopService.findByQueryCount(query);
            return AjaxResult.success().setData(byQuery).setTotal(total);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    //
    @GetMapping("/export")
    public void export(HttpServletResponse response){
        try {
            List<Shop> all = shopService.findAll();
            ExcelUtil.exportExcel(all,"店铺表头","店铺信息副标题",Shop.class,"shop.xlsx",true,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

